package cn.com.git.admin.server.ctrler;

import cn.com.git.admin.common.UpmsConstant;
import cn.com.git.admin.common.UpmsResultConstant;
import cn.com.git.admin.service.dto.AuthenticationDTO;
import cn.com.git.admin.service.dto.AuthenticationTokenDTO;
import cn.com.git.common.base.BaseController;
import cn.com.git.common.exception.ApiException;
import cn.com.git.common.model.ResultMsg;
import cn.com.git.common.util.security.CodecUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 入口
 */
@Controller
public class GlobalCtrler extends BaseController {

    /**
     * 登录页面
     * @return
     */
    @GetMapping({"/login"})
    public ModelAndView login(HttpSession session) {
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    /**
     * 登录入口
     * @param username 用户名称（账号）
     * @param password 密码
     * @param session
     * @param redirectAttrs
     * @param request
     * @return
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam(value = "username",required = true) String username,
                        @RequestParam(value = "password",required = true) String password,
                        HttpSession session, RedirectAttributes redirectAttrs, HttpServletRequest request) {
        ResultMsg resultMsg = null;
        /*  登录校验 */
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, CodecUtils.MD5(password));
        AuthenticationDTO authenticationDTO = null;
        try {
            subject.login(token);
            authenticationDTO = subject.getPrincipal()==null?null:(AuthenticationDTO)subject.getPrincipal();
        } catch (UnknownAccountException e) {
            resultMsg = new ResultMsg(UpmsResultConstant.FAILED,null,"用户名或密码错误，请重新输入！");
        } catch (IncorrectCredentialsException e) {
            resultMsg = new ResultMsg(UpmsResultConstant.FAILED,null,"用户名或密码错误，请重新输入！");
        } catch (LockedAccountException e) {
            resultMsg = new ResultMsg(UpmsResultConstant.FAILED,null,"该用户已被禁用！");
        } catch (Exception e) {
            resultMsg = new ResultMsg(UpmsResultConstant.FAILED);
            e.printStackTrace();
        }
        //根据登录结果，返回页面
        if (resultMsg != null) {
            redirectAttrs.addFlashAttribute("resultMsg", resultMsg);
            redirectAttrs.addFlashAttribute("username", username);
            return "redirect:/login";
        } else {
            //将用户信息保存到session
            session.setAttribute(UpmsConstant.SESSION_SYS_USER, authenticationDTO);
            return "redirect:/index";
        }
    }

    /**
     * 系统登出
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(UpmsConstant.SESSION_SYS_USER);
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }


    /**
     * 系统主页
     * @return
     */
    @RequestMapping(value = {"","/","/index"},method = RequestMethod.GET)
    public ModelAndView index() {

        ModelAndView mv = new ModelAndView("index");
        return mv;
    }

    /**
     * 系统欢迎页
     * 现在暂时为空
     * @return
     */
    @RequestMapping(value = "/home/index", method = RequestMethod.GET)
    public String home() {
        return "home/index";
    }

    /**
     * 全局异常处理
     * @param request
     * @param e
     * @return
     * @throws Throwable
     */
    @ExceptionHandler( {ApiException.class, Exception.class, RuntimeException.class})
    @ResponseBody
    protected ModelAndView exceptionHandler(HttpServletRequest request, Throwable e) throws Throwable {
        logger.error("异常日志：",e);
        ModelAndView mv = new ModelAndView("error");
        String path = request.getContextPath();
        mv.addObject("ctx",path);
        return mv;
    }
}
